﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Questionnaire.Models;

namespace Questionnaire.Controllers
{
    public class HomeController : Controller
    {
        private readonly IHttpContextAccessor _accessor;
        private readonly DataContext _context;
        public HomeController(IHttpContextAccessor accessor, DataContext context)
        {
            _accessor = accessor;
            _context = context;
        }

        public IActionResult Index()
        {
            var paper = _context.Papers.FirstOrDefault(q => q.Code == WebConfig.QuestionnaireCode);
            ViewBag.Title = paper?.Name;

            return View();
        }

        public IActionResult Question()
        {
            var paper = _context.Papers.FirstOrDefault(q => q.Code == WebConfig.QuestionnaireCode);
            ViewBag.Title = paper?.Name;

            var questions = new List<Question>();
            var selections = new List<Selection>();

            if (paper != null)
            {
                questions = _context.Questions.Where(q => q.PaperId == paper.Id).OrderBy(q => q.Sort).ToList();

                var questionIds = questions.Select(q => q.Id).ToList();

                selections = _context.Selections.Where(s => questionIds.Contains(s.QuestionId)).ToList();
            }
            ViewData["Selections"] = selections;
            return View(questions);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Submitted()
        {
            long replierId = 0;

            var paper = _context.Papers.FirstOrDefault(q => q.Code == WebConfig.QuestionnaireCode);
            if (paper != null)
            {
                var answers = translateFormData(Request.Form);

                if (answers.Count > 0)
                {
                    var maxId = _context.Repliers.Count() > 0 ? _context.Repliers.Max(r => r.Id) : 0;
                    var replier = new Replier()
                    {
                        PaperId = paper.Id,
                        Name = "游客用户" + (maxId + 1),
                        ClientIP = _accessor.HttpContext?.Connection?.RemoteIpAddress?.ToString(),
                        CreateTime = DateTime.Now
                    };

                    if (saveReplierAndAnswers(replier, answers))
                    {
                        replierId = replier.Id;
                    }
                }
            }
            return RedirectToAction("Contact", new { replierId });
        }

        #region 保存辅助方法

        private List<Answer> translateFormData(IFormCollection form)
        {
            var answers = new List<Answer>();
            form.Where(p => p.Key.StartsWith("question_")).ToList().ForEach(pair =>
                {
                    pair.Value.ToList().ForEach(value =>
                    {
                        answers.Add(new Answer
                        {
                            QuestionId = long.Parse(pair.Key.Replace("question_", "")),
                            SelectionId = long.Parse(value)
                        });
                    });
                });
            return answers;
        }

        private bool saveReplierAndAnswers(Replier replier, List<Answer> answers)
        {
            using (var transaction = _context.Database.BeginTransaction())
            {
                try
                {
                    _context.Repliers.Add(replier);
                    if (_context.SaveChanges() > 0)
                    {
                        answers.ForEach(answer =>
                        {
                            answer.ReplierId = replier.Id;
                        });
                        _context.Answers.AddRange(answers);
                        if (_context.SaveChanges() > 0)
                        {
                            transaction.Commit();
                            return true;
                        }
                    }
                    transaction.Rollback();
                    return false;
                }
                catch
                {
                    transaction.Rollback();
                    return false;
                }
            }
        }


        #endregion 保存辅助方法

        public IActionResult Contact()
        {
            var paper = _context.Papers.FirstOrDefault(q => q.Code == WebConfig.QuestionnaireCode);
            ViewBag.Title = paper?.Name;

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Saved()
        {
            long replierId = long.Parse(Request.Query["replierId"]);

            if (replierId > 0)
            {
                var replier = _context.Repliers.Find(replierId);
                if(replier != null)
                {
                    replier.Name = Request.Form["name"];
                    replier.Mobile = Request.Form["mobile"];
                    _context.Entry(replier).State = EntityState.Modified;
                    _context.SaveChanges();
                }
            }
            return RedirectToAction("Okay");
        }

        public IActionResult Okay()
        {
            var paper = _context.Papers.FirstOrDefault(q => q.Code == WebConfig.QuestionnaireCode);
            ViewBag.Title = paper?.Name;

            return View();
        }

        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
}
